std::format
accepts a format string composed of ordinary text and replacement fields (surrounded with {}
) that are
replaced with a textual representation of the remaining std::format
arguments. This allows generating a complex string with a single
invocation of std::format
.
Since calls to std::format
produce string objects, it is possible to concatenate them with other string objects or string literals.
However, compared to a single std::format
invocation with an adjusted format string, this concatenation is inefficient and less
readable.
This rule raises an issue when the concatenation performed on the result of std::format
can be replaced with a single
std::format
invocation.
Noncompliant code example
void formatExamples(std::string str, char const* cstr, int i) {
std::string s1 = "You have been greeted " + std::format("{}", i) + " times."; // Noncompliant
std::string s2 = "Hello " + std::format("{:*^20}", str) + "! " + std::format("{:->15}", cstr) + '.'; // Noncompliant
}
Compliant solution
void formatExamples(std::string str, char const* cstr, int i) {
std::string s1 = std::format("You have been greeted {} times.", i); // Compliant
std::string s2 = std::format("Hello {:*^20}! {:->15}.", str, cstr); // Compliant
}
std::string fullName(std::string name, std::string secondName, std::string surname, std::size_t number) {
// Compliant, as the formatted output depends on runtime properties
std::string result = std::format("({}) {}", number, name);
if (!secondName.empty()) {
result += " ";
result += secondName.front();
}
result += surname;
return result;
}